package com.example.main.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class VirtualThreadExample {
    public static void main(String[] args) {
        // 创建一个虚拟线程的线程池
        ExecutorService executor = Executors.newThreadPerTaskExecutor(
                Thread.ofVirtual().name("virtual-thread-", 0).factory()  //设置名称
        );
        //另一种方式创建虚拟线程的线程池，二者等价
        ExecutorService executor2 = Executors.newVirtualThreadPerTaskExecutor();
        int numberOfTasks = 100; // 提交1万个任务
        for (int i = 0; i < numberOfTasks; i++) {
            executor2.submit(() -> {
                System.out.println("Task executed by: " + Thread.currentThread().getName());
            });
        }
        // 关闭线程池
        executor.shutdown();
        System.out.println("All tasks submitted.");


        //虚拟线程根本不需要什么线程池（除非为了和以前普通线程接口调用保持一致），直接生成更简单
        Runnable task = () -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("Virtual Thread: " + i);
            }
        };
        Thread virtualThread = Thread.ofVirtual().start(task);
        try {
            virtualThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Main thread finished with virtual thread.");
    }
}
